Repository navigation
Combat 4.2: Cache entity stat snapshots and snapshot projectiles at launch - #385
Merged
Merged
Conversation
Times hits per second for two situations, hits that follow each other with nothing in between and one hit per tick, with the same fighters and gear every run. It only runs with -Dcombat.benchmark=true, so it costs the suite nothing. It exists to put numbers on the stat snapshot change that follows. Claude-Session: https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ
Every hit used to read every damage type, defense and item stat from every equipped item of both fighters. EntityStats now keeps a snapshot per entity: each damage type's minimum and maximum summed over the equipment, each defense, each item stat and each enchantment protection factor, filled in on demand. The roll of a damage range, the biome, and active effects are still applied at the hit, so the distribution of results and the charges of an effect are what they were. A snapshot is dropped when equipment or held items change, when a set, class or profile asks for a forced refresh, when profile buffs change or run out, on death, on quit, and when a stats config reload clears the registries. The refresh a hit asks for on the next tick only drops it if the equipment or bonus maps differ from what it was built from; wear is not a difference. Vanilla armor and toughness attributes are compared each time they are used. A maximum age (performance.entity-stats.snapshot-max-age, 20 ticks, 0 turns the cache off) covers changes that nothing announces. A projectile records a frozen snapshot of its shooter when it is launched, including active effects, and the hit at impact uses it. Gear swapped or buffs gained after firing no longer affect an arrow in flight. Projectiles without a snapshot are read at impact, as before. Claude-Session: https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ
- A launch snapshot records its shooter; a projectile that has changed hands is read live at impact. - Only projectiles that can deal damage get a snapshot. The set comes from AmmoAttribute.Type plus AbstractArrow; pearls, snowballs, eggs, bottles and hooks keep being read at impact. - Effects are captured at launch without using their charges. The hit that lands uses them, so a miss or a projectile that deals no damage spends none. - snapshot-max-age 0 is a real off switch: no items are copied and nothing is kept. - The sweep keeps the snapshot of a projectile whose chunk is unloaded and releases it when the projectile cannot be found in a loaded chunk or is dead, with a ten minute upper bound. - A plugin reload clears launch snapshots as well as live ones. - Reading buff expiry off the main thread can no longer throw. Claude-Session: https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #372. Part of #365.
Every hit read every damage type, defense and item stat from every equipped item of both fighters.
EntityStatsnow keeps a snapshot per entity and rolls ranges at hit time. A projectile that can deal damage records its shooter's snapshot at launch and uses it at impact.1. What a hit read before (melee, per hit)
VanillaWrapperListener#onVanillaDamage→EntityStats#getDamageTypesDamageAttribute#get, parses item PDC andStatBonusconditions), set/class bonus functions, profile buff (onegetOrLoadUserper type), then roll, biome, effectsgetItemStatsSimpleStat#get, incl. gem socket lookup), plus the toughness attributegetDefenseTypesDamageManager#handleDamageModifiers, calculator setup, thornmailDamageManager#getEnchantModifier→getEnchantProtectFactorscaleValuesWithCoreAttributeRegistry/BuffRegistryper damage and defense typecustom-cooldown, attackerATTACK_DAMAGEattribute, vanilla weapon damageDamageManagerDamageCalculatoritself reads nothing: it gets plain numbers fromDamageManager.Already cached by
EntityStats:inventory(the usable equipped items) andbonuses(set and class bonus functions), both rebuilt inupdateAll(). The old comment said damage was "not cached due to broke of range values". The snapshot sits on top of these and is validated against them; it is not a second cache.After every completed hit,
EntityManageralso schedulesupdateAll()for both fighters on the next tick. That matters for the design (see "Why the refresh after a hit is different").2. Snapshot contents and the maths
Filled in on demand, per entity (
StatSnapshot):RANGE_FULLadds every item's min and max before anything is rolled)Applied at the hit, on every read, and never cached: the roll (
Rnd.getDouble(min, max), same single call per type, same order), the biome, active effects (AdjustStatEffecthas charges and expires by itself), and an item stat's cap.Rolled-then-summed question (constraint 2): no stat is rolled per item. Items are summed first and the sum is rolled once, so caching
{min, max}keeps the distribution. Proven by a seeded test: the first five rolls for seed 1234 are hard-coded from the base commit's output and match, and cached and uncached sequences are identical.3. Invalidation
EntityManager#onEntityUpdateEquipmentChange→ forcedupdateAll()next tickEntityManager#onStatsUpdatePlayerHeld→ forcedupdateAll()SetManager#onSetUpdateEquip→updateSets→updateAll()onStatsJoin,onStatsUpdatePlayerRespawn,onStatsUpdateMobSpawn→ forcedrefreshAfterHit()compares equipment with the snapshot's own copies and drops it if different. Same one-hit lag as beforeSetManager#updateSets→updateAll(); bonus maps also compared by identity after a hitClassManager#updateClassData→updateAll()ProfileManager#switchProfile→updateAll(); snapshot also checks the active profile objectUserProfilerevision counter, compared on each use;BuffCommandcallsmarkBuffsChanged()validUntil = min(max age, next buff expiry)scaleValuesWithCoreEntityStats#handleDeath(player: dropped; mob: purged)EntityManager#onStatsQuit→purgeEntityStats#getAll()sweeps invalid entities every tick (EntityStatsTask); launch snapshots: see section 4Divinity#disablecallsItemStats.clear()(which callsinvalidateAllSnapshots), then purges everyEntityStats, thenProjectileStats.clear(). So live snapshots go with the purged stats and launch snapshots are cleared; an arrow in flight across a reload is read at impact as before. Registering a stat also invalidates. Covered by a test that reloads the pluginperformance.entity-stats.snapshot-max-age, 20 ticks, 0 turns the cache offWhere there is no reliable event: vanilla attribute changes (potions, other plugins), direct edits to buff sets, level changes made by another plugin, gear set silently by a plugin. Attributes are compared; the rest fall back to the max age. 1 second is a bound on staleness, and a rebuild costs about one old hit, so even a hit every second does no worse than before. Level requirements are decided when the equipment list is rebuilt, as before; that is unchanged.
snapshot-max-age: 0is a true off switch. Nothing is stored and no items are copied (a test checksStatSnapshot.copyOfis never called); each read works from a throwaway snapshot, which is the old cost.Why the refresh after a hit is different. Because each hit schedules
updateAll()for both fighters, dropping the snapshot there would leave it never alive at the next hit.updateAll()still always drops it (class, profile, set callers). A newrefreshAfterHit(), used only by that post-hit path, drops it only if the equipment or bonus maps differ.Thread safety. Exposure is the same as before, plus one guard. The equipment list is copied under its own lock; each section of a snapshot is filled under the snapshot's lock and never changed afterwards; the bonus list copy cannot throw. Reading buff sets off the main thread (a placeholder read) could throw
ConcurrentModificationExceptionbefore this PR as well (UserProfile#getBuffstreams over them), so that is not new. The one new iteration,getNextBuffExpiry, catches it and answers "expires now", so nothing is cached from a read that raced.4. Projectiles
Carried today as metadata on the projectile:
QRPG_PJ_WEAPON(the bow),QRPG_PJ_POWER,QRPG_ARROW_ID/LEVEL. Stats were read at impact from the shooter's current gear with the main hand replaced by the bow.Now:
onProjectileLaunchSnapshot(MONITOR, after all other launch handlers) stores a frozenStatSnapshotwith the bow in place of the main hand, the custom arrow's bonus, active effects and the shooter's biome. Impact rolls from it. Weapon and power handling is unchanged.ProjectileStats#canDealDamage:AbstractArrow(arrows, spectral arrows, tridents) plus the kinds inAmmoAttribute.Typethat deal damage (fireball, wither skull, shulker bullet, llama spit). Pearls, snowballs, eggs, bottles and hooks are skipped and read at impact as before. The set comes fromAmmoAttribute.Type, which now says which kinds deal damage, rather than a new list.ProjectileStats, not metadata, because I believe entity metadata is only cleared when someone removes it (not verified against a server here).ProjectileStats#sweep(every 100 ticks) releases an entry when the projectile is found dead, or cannot be found although the chunk it was last seen in is loaded. A projectile in an unloaded chunk keeps its snapshot. A ten minute upper bound from launch applies to everything, as a safety net.Intended behaviour changes (two):
A projectile with no snapshot is read at impact as before.
5. Benchmark
CombatBenchmark(opt-in,-Dcombat.benchmark=true). A geared attacker (3 damage types, 3 stats) hits a victim in 4 armor pieces (3 defenses, 2 stats each) through the real listener. 5 rounds, median, MockBukkit.aed8234)Rounds before: burst 54 53 50 49 51, steady 44 38 40 37 33. After: burst 296 276 288 290 269, steady 136 123 117 108 96. (The run before the review fixes gave 281 and 109.) MockBukkit item parsing is far slower than a server, so read these as ratios.
What is deliberately not included
updateAll()far more often, and the existing paths plus the post-hit compare already cover them.DamageCalculator(4.1 changes it); the calculator is untouched.Tests
EntityStatSnapshotTest(39: one per trigger above, launch snapshot, release on death, quit, removal, projectile removal, seeded and statistical rolls) andProjectileLaunchSnapshotTest(13: shooter change viasetShooter, two projectiles with different gear, a custom arrow's bonus carried to impact, which projectiles get a snapshot, charges at impact, hold times, reload, off switch).Tests run: 236, Failures: 0, Errors: 0, Skipped: 2, exit 0. The 2 skipped are the expected trident tests. CI is green on the previous head and runs again on this one.Break-it checks (each applied, run, reverted)
updateAll()stops dropping the snapshotinvalidateAllSnapshotsdoes nothingaProjectileThatChangedHands_...)isShooteralways trueanArrowThatIsLaunched_butNeverHits_spendsNoCharge)anArrowThatHits_spendsExactlyOneCharge_...)arrowsGetASnapshot_pearlsAndSnowballsDoNot)aReload_..., a real plugin reload)Decisions taken from review
🤖 Generated with Claude Code
https://claude.ai/code/session_01FaEyTrj2kNoybQssGMYRpJ